package com.ideaction.service;

import com.alibaba.fastjson.JSONObject;
import com.ideaction.datacertify.PlayerDataCertifyManager;
import com.ideaction.entity.player.Player;
import com.ideaction.entity.player.ResourceData;
import com.ideaction.game.utils.IpUtils;
import com.ideaction.game.utils.SimpleDBUtil;
import com.ideaction.globalconst.NoticeKeyConst;
import com.ideaction.globalconst.Result;
import com.ideaction.log.dblog.RegistLog;
import com.ideaction.req.PlayerCommonReqBody;
import com.ideaction.req.PlayerSaveReqBody;
import com.ideaction.utils.sms.SmsKit;
import com.log.service.GameLogService;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PlayerServiceImp {
    
    @Autowired
    private MongoTemplate playerMongoTemplate;
    
    @Autowired
    private GameLogService gameLogService;
    
    public String savePlayer(PlayerSaveReqBody playerSaveReqBody, String ip) {
        Result r = Result.build();
        String userId = playerSaveReqBody.getUserId();
        Player player;
        if (!SimpleDBUtil.existsPlayer(playerMongoTemplate, userId)) {
            player = new Player(userId, ip, playerSaveReqBody);
            log.info("自动注册玩家,userId: " + userId + " ip: " + ip);
            RegistLog dblog = new RegistLog(playerSaveReqBody.getUserId(), ip);
            gameLogService.dbExcute(dblog);
        } else {
            player = SimpleDBUtil.findDataByUserId(playerMongoTemplate, userId, Player.class);
            JSONObject upData = playerSaveReqBody.getPlayerClientData();
            JSONObject oldData = player.getPlayerClientData();
            long createTime = player.getCreateTime();
            long passTime = System.currentTimeMillis() / 1000 - player.getSaveTime();
            //todo  前面加一个验证总开关,根据配置去加
//            if(){
//
//            }
//            r = PlayerDataCertifyManager.certifyPlayerClientData(upData, oldData, passTime, ip, createTime);
//            //验证失败直接返回
//            if(!r.isOk()){
//                return r.response();
//            }
        }
        log.info("savePlayer success  userId:"+userId);
        player.setPlayerClientData(playerSaveReqBody.getPlayerClientData());
        playerMongoTemplate.save(player);
        return r.response();
    }
    
    /**
     * 修改角色名
     *
     * @return
     */
    public String changeName(PlayerCommonReqBody playerCommonReqBody) {
        String userId = playerCommonReqBody.getUserId();
        String userName = playerCommonReqBody.getParam("UserName");
        String language = playerCommonReqBody.getParam("Language");
        
        Result r = Result.build();
        if (SimpleDBUtil.existsPlayer(playerMongoTemplate, userId)) {
            Query query = new Query(Criteria.where("userId").is(userId));
            Update update = new Update();
            update.set("userName", userName);
            if (playerMongoTemplate.upsert(query, update, Player.class).getModifiedCount() < 1) {
                log.warn("changeName ModifiedCount = 0, userId=" + userId + ", userName=" + userName);
                return r.error(NoticeKeyConst.USER_ID_NOT_EXIST, language);
            }
        } else {
            log.warn("changeName not find player, userId=" + userId + ", userName=" + userName);
            return r.error(NoticeKeyConst.USER_ID_NOT_EXIST, language);
        }
        
        return r.response();
    }
    
    /**
     * 绑定手机号
     *
     * @return
     */
    public String phoneBind(PlayerCommonReqBody playerCommonReqBody) {
        String userID = playerCommonReqBody.getUserId();
        String phoneNum = playerCommonReqBody.getParam("PhoneNum");
        String checkCode = playerCommonReqBody.getParam("CheckCode");
        String zone = playerCommonReqBody.getParam("Zone");
        String language = playerCommonReqBody.getParam("Language");
        
        Result r = Result.build();
        
        // 验证码是否为空
        if (checkCode == null || "".equals(checkCode)) {
            return r.error(NoticeKeyConst.PHONE_CODE_ERR, language);
        }
        
        if (!SmsKit.checkCodeVerify(phoneNum, zone, checkCode)) {
            return r.error(NoticeKeyConst.PHONE_CODE_ERR, language);
        }
        
        if (SimpleDBUtil.existsPlayer(playerMongoTemplate, userID)) {
            Query query = new Query(Criteria.where("userId").is(userID));
            Update update = new Update();
            update.set("phoneNum", phoneNum);
            if (playerMongoTemplate.upsert(query, update, Player.class).getModifiedCount() < 1) {
                log.warn("changeName ModifiedCount = 0, userId=" + userID);
                return r.error(NoticeKeyConst.USER_ID_NOT_EXIST, language);
            }
        } else {
            log.warn("changeName not find player, userId=" + userID);
            return r.error(NoticeKeyConst.USER_ID_NOT_EXIST, language);
        }
        
        return r.response();
    }
    
    /**
     * 客户端心跳时间检查
     *
     * @return
     */
    public String checkTimeStamp(PlayerCommonReqBody playerCommonReqBody) {
        String userID = playerCommonReqBody.getUserId();
        String clientTime = playerCommonReqBody.getParam("ClientTime");
        String language = playerCommonReqBody.getParam("Language");
        
        Result r = Result.build();
        return r.response();
    }
    
    /**
     * 根据玩家id查询玩家
     *
     * @param userId
     * @return
     */
    public Player findPlayer(String userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return playerMongoTemplate.findOne(query, Player.class);
    }
    
    public void addDiamond(String userId, int diamond) {
        Query userId1 = Query.query(Criteria.where("userId").is(userId));
        Update update = new Update();
        update.inc("playerClientData.diamond", diamond);
        UpdateResult updateResult = playerMongoTemplate.updateFirst(userId1, update, Player.class);
    }
    
    public ResourceData findPlayerResource(String userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return playerMongoTemplate.findOne(query, ResourceData.class);
    }
    
    public void clearPlayer(String userId) {
        
        Player player = findPlayer(userId);
        if (player != null) {
            playerMongoTemplate.remove(player);
        }
    }
}
